package com.minyifang.wcspf.common.utils;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.minyifang.wcspf.R;


/**
 * @description 用于显示操作状态的Toast工具类
 * Created by xuyougen on 2017/11/10.
 */

public class ToastHelper {

    private Context mContext;
    private static ToastHelper INSTANCE = null;

    //三种状态的图标
    private int[] icons = {
            R.drawable.ic_toast_success,
            R.drawable.ic_toast_error,
            R.drawable.ic_toast_warn};

    //三种状态标记（值和上面图标的索引值是对应的）
    private static final int TYPE_SUCCESS = 0;
    private static final int TYPE_ERROR = 1;
    private static final int TYPE_WARN = 2;
    private Toast mToast;

    //私有构造
    private ToastHelper(Context context) {
        mContext = context;
    }

    //获取实例
    public static ToastHelper getInstance(Context context) {
        if (INSTANCE == null) {
            synchronized (ToastHelper.class) {
                INSTANCE = new ToastHelper(context.getApplicationContext());
            }
        }
        return INSTANCE;
    }

    public void showNormal(String content) {
        generateToast(content, -1);
    }

    /**
     * 显示成功Toast（对勾图标）
     *
     * @param content 上下文
     */
    public void showSucceed(String content) {
        generateToast(content, TYPE_SUCCESS);
    }

    /**
     * 显示错误/失败Toast（叉叉图标）
     *
     * @param content 上下文
     */
    public void showError(String content) {
        generateToast(content, TYPE_ERROR);
    }

    /**
     * 显示警告/提示Toast（感叹号图标）
     *
     * @param content 上下文
     */
    public void showWarn(String content) {
        generateToast(content, TYPE_WARN);
    }


    /**
     * 根据类型生成相对应的Toast
     *
     * @param content 显示内容
     * @param type    类型
     */
    private void generateToast(String content, int type) {
        if (mToast==null){
            mToast = new Toast(mContext);
        }

        View mLayoutView = View.inflate(mContext, R.layout.toast_layout, null);
        ImageView icon = (ImageView) mLayoutView.findViewById(R.id.mTvToastIcon);

        if (type != -1) {
            //根据类型设置图标
            icon.setImageResource(icons[type]);
        }else{
            icon.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(content)) {
            TextView textView = (TextView) mLayoutView.findViewById(R.id.mTvToastContent);
            textView.setText(content);
        }

        mToast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, (int) (mContext.getResources().getDisplayMetrics().density * 100));
        mToast.setView(mLayoutView);
        mToast.show();
    }

}
